package com.demo.config.rabbitMq;

import com.demo.mapper.DemoMapper;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 消费者
 */
@Component
public class MsgListener {

	@Resource
	private DemoMapper mapper;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@RabbitListener(queues = "direct_queue")
	public void receive(String content) {
		// int insert = insert(content);
		System.out.println("已完成短信发送业务（rabbitmq）1" + content);
	}

	@RabbitListener(queues = "topic_queue")
	public void receive1(String content) {
		if (checkParam(content)) {
			// int insert = insert(content);
			System.out.println("topic_queue已完成短信发送业务（rabbitmq）" + content);
		}
	}

	@RabbitListener(queues = "topic_queue2")
	public void receive2(String content) {
		if (checkParam(content)) {
			// int insert = insert(content);
			System.out.println("topic_queue2已完成短信发送业务（rabbitmq）" + content);
		}
	}

	/**
	 * 判断redis中是否存在数据 存在-false 不存在-true
	 * @param content
	 * @return
	 */
	public Boolean checkParam(String content) {
		System.out.println(redisTemplate.hasKey(content));
		if (Boolean.FALSE.equals(redisTemplate.hasKey(content))) {
			redisTemplate.opsForValue().set(content, content, 1000, TimeUnit.SECONDS);
			return true;
		}
		return false;
	}

	/**
	 * 新增数据
	 * @param content
	 * @return
	 */
	public int insert(String content) {
		try {
			return mapper.insert(Integer.valueOf(content));
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
